//
// Created by leisurexi on 12/5/20.
// reuseadr_eserver.c
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define TRUE 1
#define FALSE 0

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock, client_sock;
    char message[30];
    int option, str_len;
    socklen_t optlen, client_addr_len;
    struct sockaddr_in server_addr, client_addr;

    if (argc != 2) {
        printf("Usage : %s <port> \n", argv[0]);
        exit(1);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock == -1)
        error_handling("socket() error");

    optlen = sizeof(option);
    option = TRUE;
    setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &option, optlen);

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    if (bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)))
        error_handling("bind() error");
    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");

    client_addr_len = sizeof(client_addr);
    client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);
    while ((str_len = read(client_sock, message, sizeof(message))) != 0) {
        write(client_sock, message, str_len);
        write(1, message, str_len);
    }
    close(client_sock);
    close(server_sock);
    return 0;
}
